package reading.common.enums;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import reading.common.CommonUtil;

/**
 * Create by txw on 2017/11/9
 * Description: springMvc枚举转换
 * DataSourceMap:
 *
 * @author txw
 **/
public class StringToEnumConverter implements ConverterFactory<String, IBaseEnum> {

    @Override
    @SuppressWarnings("unchecked")
    public <T extends IBaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        if (!targetType.isEnum()) {
            throw new UnsupportedOperationException("只支持转换到枚举类型");
        }
        return new StringToBaseEnumConverter(targetType);
    }

    private class StringToBaseEnumConverter<T extends IBaseEnum> implements Converter<String, T> {
        private final Class<T> enumType;

        public StringToBaseEnumConverter(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Override
        public T convert(String s) {
            if (CommonUtil.isNullAndNullStr(s)) {
                return null;
            }
            for (T t : enumType.getEnumConstants()) {
                if (Integer.valueOf(s) == t.getValue()) {
                    return t;
                }
            }
            return null;
        }
    }

}
